#! /usr/bin/env python
import os
from datetime import datetime, timedelta

import sys
sys.path.insert(0, '../lib')
from scapy.all import *
import plan


def tftp_monitor_callback(interval):
    def tftp_monitor(pkt):
        if TFTP in pkt and pkt[TFTP].op == 1 and "01-" in str(pkt.filename):
            mac = os.path.basename(str(pkt.filename))[3:].replace('-', ':')
            print '%s %s => %s' % (datetime.now().strftime('%Y/%m/%d-%H:%M:%S'), str(pkt.filename), 'caped')
            # sleep a while to let client to download the pxe file
            # TODO: still block process. should use sched?
            time.sleep(0.1)
            res = 'add' if plan.ack(mac, interval) else 'skip'
            print '%s %s => %s' % (datetime.now().strftime('%Y/%m/%d-%H:%M:%S'), str(pkt.filename), res)
        return None
    return tftp_monitor


if __name__ == '__main__':
    interval = 5
    if len(sys.argv) > 1:
        interval = int(sys.argv[1])
    sniff(
        prn=tftp_monitor_callback(interval),
        filter="port tftp",
        store=0)
